﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataTier;
using System.Data.SqlClient;
using System.Data.Common;


namespace DbLayer
{
    public class DbConnection : DbObject, IDbConnection
    {

        private static DbConnection _instance;
        private IDbLocation _dbLocation = DbLocation.Instance;

        public static IDbConnection Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new DbConnection();
                }
                return _instance;
            }
        }

        private DbConnection()
        {
        }

        public void AddConnection(Connection connection)
        {
            string statement = BuildInsertStatement("Connection", connection.Weight.ToString(), connection.From.Id.ToString(), connection.To.Id.ToString());
            ExecuteStatement(statement);
        }

        public IList<Connection> GetConnections(int locationId)
        {

            List<Connection> connections = new List<Connection>();
            string statement = BuildSelectStatement("Connection", "fromId = '" + locationId.ToString() + "' OR toId = '" + locationId.ToString() + "'");
            SqlDataReader reader = ExecuteQuery(statement);

            while (reader.Read())
            {
                connections.Add(BuildConnection(reader));
            }

            reader.Close();

            return connections;

        }

        public IList<Connection> GetAllConnections()
        {

            List<Connection> connections = new List<Connection>();
            string statement = BuildSelectStatement("Connection", "");
            SqlDataReader reader = ExecuteQuery(statement);

            while (reader.Read())
            {
                connections.Add(BuildConnection(reader));
            }

            reader.Close();

            return connections;

        }

        private Connection BuildConnection(SqlDataReader reader)
        {

            Connection connection = new Connection();

            connection.From = _dbLocation.GetLocation(Convert.ToInt32(reader["FromId"]));
            connection.To = _dbLocation.GetLocation(Convert.ToInt32(reader["ToId"]));
            connection.Weight = Convert.ToInt32(reader["weight"]);

            return connection;

        }


    }
}
